<template>
	<div class="l-r"  v-loading="loading"
		element-loading-text="拼命加载中">
		<div class="knowledge-warp-l-nav">

			<div class="knowledge-warp-l-nav-type">
				<el-radio-group v-model="itemBankType" @change="getTestList()">
					<el-radio label="default">公共题库</el-radio>
					<el-radio label="private">私人题库</el-radio>
				</el-radio-group>
			</div>
			
			<!-- <label for="switch-l" class="switch-l">
				<input id="switch-l" type="checkbox" name="nav" v-model="isscrollbar">
			</label> -->
			
			<div class="nav-class">
				<span v-if="!isscrollbar"><i class="el-icon-arrow-up"></i>收起</span>
				<span v-else><i class="el-icon-arrow-down"></i>展开</span>
			</div>
			<input type="checkbox" name="nav" v-model="isscrollbar">
				
			<ul class="question-bank-h-type">

				<li class="question-bank-h-list">
					<span>题型:</span>
					<div>
						<template>
						  <el-radio-group v-model="question.type" @change="getTestList()">
						  	<template v-for="item of questionTypeList">
						  		<el-radio :label="item.id">{{item.name}}</el-radio>
						  	</template>
						  </el-radio-group>
						</template>
					</div>
				</li>

				<li class="question-bank-h-list">
					<span>难度:</span>
					<div>
						<template>
						  <el-radio-group v-model="question.difficulty" @change="getTestList()">
						    <el-radio :label="0">全部</el-radio>
						    <el-radio :label="11">容易</el-radio>
						    <el-radio :label="12">普通</el-radio>
						    <el-radio :label="13">困难</el-radio>
						  </el-radio-group>
						</template>
					</div>
				</li>

				<li class="knowledge-points-area">
                    <el-row type="flex" align="middle">
                        <el-col :span="3">
                            <span class="title">试卷范围:</span>
                        </el-col>     
                        <el-col :span="15">
                            <testArea ref="testArea" @changeArea="changeArea"></testArea>
                        </el-col> 
                        <el-col :span="5">
                            <el-button type="primary" @click="getTestList()">筛选</el-button>
                            <el-button type="primary" plain @click="restChange()">重置</el-button>                            
                        </el-col>                                                         
                    </el-row>
				</li>

				<li class="question-bank-h-list">
					<span>{{optionVal == 1 ? '章节' : '知识点'}}:</span>
					<div >

						
						<template v-if="optionVal == 1">
								<el-cascader :options="chapterList"  placeholder= '选择章节'
								 filterable clearable
								 v-model="question.chapter"
								 @focus="setMaterial"
								@change="chapterChange">
								</el-cascader>
						</template>
						<template v-else>
							<el-cascader :options="knowledgeList"  placeholder= '选择知识点'
							filterable clearable
							 v-model="question.knowled"
							 @focus="setMaterial"
							@change="knowledgeChange">
							</el-cascader>
						</template>

						<el-popover placement="top"  width="200" v-model="visibleType" v-if="0">
							<div class="bank-option">
								<el-radio-group v-model="optionVal" size="small" @change="getOption">
									<el-radio label="1" border>选择知识点</el-radio>
									<el-radio label="2" border>选择章节</el-radio>
								</el-radio-group>
							</div>
							<el-button slot="reference" type="text">选择形式	</el-button>
						</el-popover>
						
						
					</div>
				</li>

			</ul>


			<div class="question-bank-wp-r-h">
				<div>
					<el-input
						placeholder="搜索试题"
						suffix-icon="el-icon-search"
						v-model="question.keyword" @change="getTestList()">
					</el-input>


					<el-radio-group v-model="question.order" @change="getTestList()">
						<el-radio label="time">最新<i class="el-icon-sort-down"></i></el-radio>
						<el-radio label="fav">热门<i class="el-icon-sort-down"></i></el-radio>
					</el-radio-group>

				</div>

			</div>
			
		</div>

		<el-scrollbar :class="{ 'knowledge-scrollbar': isscrollbar}">
		
			<ul class="preview-conten-subject">

				<template v-for="(item, index) of testList">
					<transition name="el-zoom-in-top">
					<li class="preview-conten-subject-c" :key="index">
						<template>
							<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
								<i>{{index+1}}. </i>
								<span v-html="item.content"></span>
								<strong v-if="item.score">({{item.score}}分)</strong>
							</div>
							<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
								<i>{{index+1}}. </i>
								<span v-html="item.content"></span>
								<strong v-if="item.score">({{item.score}}分)</strong>
							</div>
						</template>

						<ul class="preview-topic" v-if="item.option">
							<template v-for="(option,index2) of item.option" >

								<li class="preview-subject-title preview-false option-pattern" v-if="item.type_base_id === 4"  :key="index2">
									<template >
										<el-checkbox disabled :label="option.name">{{option.name}}</el-checkbox>
									</template>
								</li>

								<template v-else>
									<li class="preview-subject-title preview-false" v-if="item.pattern === 1" :key="index2">
										<template>
											<el-checkbox disabled :label="option.name"></el-checkbox>
											<div  v-html="option.value"></div>
										</template>
									</li>

									<li class="preview-subject-title preview-false option-pattern" v-if="item.pattern === 2"  :key="index2">
										<template >
											<el-checkbox disabled :label="option.name"></el-checkbox>
											<!-- <div  v-html="option.value"></div> -->
										</template>
									</li>
								</template>
								
							</template>
						</ul>

						<el-collapse accordion class="preview-answer">
							<el-collapse-item>
								<template slot="title">
									<div class="preview-accordion-title">
										<span>题型：{{item.question_type}}</span>
										<span>难度： {{item.difficulty}}</span>
										<span v-if="item.keynote == 1">重点程度： 低</span>
										<span v-if="item.keynote == 2">重点程度： 中</span>
										<span v-if="item.keynote == 3">重点程度： 高</span>
									</div>
									<div class="accordion-operate" @click.stop="">
										<transition name="el-fade-in-linear">
											<a class="accordion-" v-show="itemBankType == 'default' "  @click.stop="operationTest($event, 1, item)">添加到我的题库</a>
										</transition>
											<el-button type="primary" v-show="item.exist == 0" v-preventReClick  @click.stop="operationTest($event, 2, item, index)"><i class="el-icon-plus"></i>加入试卷</el-button>

											<el-button type="info" v-show="item.exist == 1"  v-preventReClick disabled>已加入试卷</el-button>
										
											<!-- <el-button type="success">已在试卷列表</el-button> -->
										
									</div>
								</template>
								<div class="preview-accordion-answer" v-if="item.type_base_id == 1 || item.type_base_id == 2 || item.type_base_id == 4">

									<span>正确答案： </span>
									<template v-if="item.type_base_id == 4">
										<div v-if="item.answer"><i>{{item.answer[0]}}</i></div>
									</template>
									<template v-else-if="item.type_base_id == 1 || item.type_base_id == 2">
										<div><i v-for="answer of item.answer">{{answer}}</i></div>
									</template>
									
								</div>
								<div class="preview-accordion-answer">
									<span>统计： </span>
									<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
								</div>
								<div class="preview-accordion-answer">
									<span>解析： </span>
									<template v-if="item.pattern == 1">
										<div v-html="item.resolve"></div>
									</template>
									<template v-if="item.pattern == 2">
										<div>
											<img :src="BASE_URL + item.resolve_path">
										</div>
									</template>
								</div>
							</el-collapse-item>
						</el-collapse>
					</li>
					</transition>
				</template>

			</ul>
		</el-scrollbar>

		<div class="dependent" v-if="placeholder">
			<i class="ipng image_state01"></i>
			<p>还没发现任何相关的内容哦~</p>
		</div>



		<!-- 预览图片 -->
		<image-viewer 
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>
	</div>
</template>

<script>
    import bus  from  './../base/eventBus.js'
    import testArea  from  './test-area';
    
	export default {
		components: { 
            testArea
        },        
		data(){
			return {
				imagePreview: {/*图片预览*/
					showViewer: false,
					previewSrcList: []
				},
				optionVal: null,
				visibleType: false,
				isscrollbar: false,
				itemBankType: 'default', /*试题 公开 || 私有*/
				question: {
					knowledge: '',
					difficulty: 0,  /*难度*/
					type: 0, 		/*试题类型*/
					order: 'time',			/*列表排序*/
					keyword: '', 			/*搜索关键字*/
					page: 1,
					size: 0,
					total: 0,
					knowled: '',
					chapter: ''
				},
				testList: [],

				questionTypeList: [], /*题型*/
				knowledgeList: [],
				chapterList: [],
				questionArray: [],
				arrayID: [],
				loading: true,
				placeholder: false,

				imgIndex: 0
				
			}
		},
		computed: {
			imageIndex() {
			    return this.imagePreview.previewSrcList.indexOf(this.imgIndex);
			},
		},
		watch: {
			'$store.state.delQuestion': {
				handler(to, from){

					if (to !== 0) {
						this.arrayID.splice(this.arrayID.indexOf(to), 1)
						for (var i = 0; i < this.testList.length; i++) {
							if (this.testList[i].id == to) {
								this.testList[i].exist = 0
								break;
							}
						}
						this.$store.commit('SET_DELQUESTION', 0)

					}
					
				},
				immediate: true
			},
		},
		created(){
			this.getQuestionType()
			bus.$on("delQuestion", (questionTyle) => {
				this.getTestList()
			})
		},
		mounted(){
			this.$nextTick(()=>{
				document.querySelector('.preview-conten-subject').addEventListener('click',  (e)=> {
					
					let [targetSrc ,imgs, srcArr, currentIdx] = ['', '', '', '']
					if (e.target.nodeName === 'IMG') {

						this.imagePreview.showViewer = true
						targetSrc = e.target.src;
						imgs = [...e.target.parentNode.children];
						srcArr = imgs.map(item=>item.currentSrc);
						currentIdx = srcArr.indexOf(targetSrc);

						this.imagePreview.previewSrcList = srcArr
						this.imgIndex = targetSrc

					}
				
				}, false)

				let manual = new Promise((resolve, reject) => {
				    //做一些异步操作
				    setTimeout(() => {
				      let manualObj =  JSON.parse(sessionStorage.getItem('manualObj'));
				        resolve(manualObj);
				    },800);
				});
				manual.then((result) => {
                    // this.$refs.testArea.edit = {
                    //     grade: result.grade,	/*年级id*/
                    //     subject: result.subject,    /*科目id*/
                    //     edition: result.edition, /*	版本id*/
                    //     material: result.course_id,	/*教材*/
                    // };
                    // this.$refs.testArea.getGrade();
				   	this.getTestList()
				})

			});
		},
		methods: {
			/**
			 * 重置数据
			 * @DateTime 2020-06-09T17:10:01+0800
			 * @qiu_m
			 * @return   {[type]}                 [description]
			 */
			restChange(){
				this.$refs.testArea.setDefault();
				this.question.page = 1;
				this.question.chapter =  '';	/*章节*/
				this.question.knowled =  '';	/*知识点*/
				this.chapterList =  [] 	/* 章节列表*/
				this.knowledgeList = []	/*知识点*/
				this.getTestList()
			},
			/**
			 * 关闭图片
			 * @DateTime 2020-04-16T17:40:41+0800
			 * @qiu_m
			 * @return   {[type]}                 [description]
			 */
			 closeViewer() {
			 	this.imagePreview.showViewer = false;
			 	this.imagePreview.previewSrcList = []
			 },
			changQuestionid(){
				return this.arrayID
			},
			/*选择知识点 || 章节数据加载*/
			getOption(type){

				this.question.chapter =  '';	/*章节*/
				this.question.knowled =  '';	/*知识点*/

			},
			/**
			 * 请求试卷列表
			 * @DateTime 2019-07-22T13:47:02+0800
			 */
			getTestList(){
	
				let success = ( res=>{
					this.testList = res.data.data;
					this.question.page = parseInt(res.data.page_index);
					this.question.total  = parseInt(res.data.data_sum);

					this.testList.map(item => item.score = 5)

					setTimeout(()=>{
						let manualObj = JSON.parse(sessionStorage.getItem('manualObj'));
						this.optionVal = manualObj.authType
					}, 500);

				/*	this.$nextTick(()=>{
						
						//改变试题 img 的 url
						let imgArr = document.querySelectorAll('.preview-conten-subject-c img')
						let baseUrl = sessionStorage.getItem('host_addr');
						for (var i = 0; i < imgArr.length; i++) {
							let _temp = imgArr[i].src
							imgArr[i].src = _temp.replace(location.protocol+'//'+location.host, baseUrl);
						}
					});*/
					this.loading = false;
					this.testList.length != 0 ? this.placeholder = false : this.placeholder = true;
				});

				/*1手动录入 2图片录入*/
				let [listid, knowid] = ['', ''];
				if (this.question.chapter.length != 0) {
					listid = deep_clone(this.question.chapter).pop()
				}
				if (this.question.knowled.length != 0) {
					knowid = deep_clone(this.question.knowled).pop()
				}

				let params = {
                    user_id: this.$g.user_id,
                    
                    grade_id: this.$refs.testArea.ruleForm.grade,
                    subject_id: this.$refs.testArea.ruleForm.subject,
                    version_id: this.$refs.testArea.ruleForm.edition,
                    masterial_id: this.$refs.testArea.ruleForm.material,   

					keyword: this.question.keyword,
					order: this.question.order,
					difficulty_id: this.question.difficulty,
					type_id: this.question.type,
					list_id: listid,/*章节id*/
					know_id: knowid,/*知识点id*/
					type: this.itemBankType,
					page_index: 0,
					page_size: 0,
				};

				// if (this.itemBankType == 'private') {
				// 	params.status = '1,2'
				// }

				this.$ajax({
					url: 'api/newtest/test_question_list',
					method: 'get',
					params: params,
					func: {success: success}
				})
			},
			/**
			 * 请求题型数据
			 * @DateTime 2019-07-25T14:04:59+0800
			 * @return   {[type]}                 [description]
			 */
			getQuestionType(){

				let success = (res=>{
					this.questionTypeList = res.data;
					if (this.questionTypeList.length > 0) {
						this.questionTypeList.unshift({id: 0, name: '全部'})
					}
				});

				let params = {status: 1};

				this.$ajax({
					url: 'api/newtest/get_question_type',
					method: 'get',
					params: params,
					func: { success: success}
				})
			},
		
			/**
			 * 请求章节数据
			 * @DateTime 2019-07-23T14:04:49+0800
			 * @return   {[type]}                 [description]
			 */
			getChapter(){
				if (this.$refs.testArea.ruleForm.material === '') {return};
				let success = (res=>{
					this.chapterList  = []

					res.data.forEach((item, index)=>{
						this.chapterList.push({
							value: item.id,
							label: item.name,
							children: []
						})

						if (item.children.length != 0) {

							item.children.forEach(child=>{
								this.chapterList[index].children.push({
									value: child.id,
									label: child.name
								})
							})
						}else{
							this.$set(this.chapterList[index], 'disabled', true)
						}


					})
				});

				let params = {}

				 params = {
					material_id: this.$refs.testArea.ruleForm.material,
					type: 1
				};

				let fail = (res=>{
					this.$message.error({
						duration: 8000,
						message: res.msg
					})
				})

				this.$ajax({
					url: 'api/newtest/get_list_know_by_material',
					method: 'get',
					params: params,
					func: {success: success, fail: fail}
				})
			},
			// 监听到试卷范围组件里面的值改变时，章节也改变
			changeArea(data){
				this.question.chapter =  '';	/*章节*/
				this.question.knowled = '';
			},
			/**
			 * 获取章节选择的id
			 * @return {[type]} [description]
			 */
			chapterChange(val) {
			  this.question.chapter = val
			  this.getTestList()
			},
			/**
			 * 请求章知识点数据
			 * @DateTime 2019-07-23T14:04:49+0800
			 * @return   {[type]}                 [description]
			 */
			getKnowledge(){
				if (this.$refs.testArea.ruleForm.material === '') {return};

				let success = (res=>{
					this.knowledgeList  = []

					res.data.forEach((item, index)=>{
						this.knowledgeList.push({
							value: item.id,
							label: item.name,
							children: []
						})

						if (item.children.length != 0) {

							item.children.forEach(child=>{
								this.knowledgeList[index].children.push({
									value: child.id,
									label: child.name
								})
							})
						}else{
							this.$set(this.knowledgeList[index], 'disabled', true)
						}


					})
				});

				let params = {}

				 params = {
					material_id: this.$refs.testArea.ruleForm.material,
					type: 2
				};

				let fail = (res=>{
					this.$message.error({
						duration: 8000,
						message: res.msg
					})
				})

				this.$ajax({
					url: 'api/newtest/get_list_know_by_material',
					method: 'get',
					params: params,
					func: {success: success, fail: fail}
				})
			},
			/**
			 * 获取知识点选择的id
			 * @DateTime 2019-09-04T11:42:45+0800
			 * @param    {[type]}                 val [description]
			 * @return   {[type]}                     [description]
			 */
			knowledgeChange(val){
				this.question.knowled = val
				this.getTestList()
			},

			/**
			 * 判断教材是否为空，在不为空时，根据id筛选相关的试题
			 * @DateTime 2019-07-24T09:27:20+0800
			 * @param    {[Strong]}   val 教材id
			 */
			setMaterial(){
				if (this.$refs.testArea.ruleForm.material != '') {
                    this.getChapter()
                    this.getKnowledge()
				}else{
					this.$refs.testArea.ruleForm.material = ''
					this.question.chapter =  '';	/*章节*/
					this.question.knowled =  '';	/*知识点*/

					this.chapterList =  [] 	/* 章节列表*/
					this.knowledgeList = []	/*知识点*/
				}

			},

			/**
			 * type 参数对应不同的函数，
			 *
			 * 1.添加到我的题库
			 * 2.加入试卷
			 */
			operationTest(e, type, obj, index){

				e.preventDefault();
				switch(type){
					case 1:
						this.$confirm('是否添加到我的题库？', '提示', {
							cancelButtonText: '取消',
							confirmButtonText: '确定',
							type: 'warning',
							customClass: "test-message"
						}).then(() => {
							let success = (res=>{
								this.$message.success(res.msg)
							});

							let params = {id: obj.id};

							this.$ajax.post('api/newtest/fav_test_question', params, {func: {success: success}})
						}).catch(() => {});
					break;
					case 2:
						// this.questionArray = [];

						/*判断用户加入的试题是否重复添*/
						if (this.arrayID.includes(this.testList[index].id)) {
							return this.$message.warning('已重复添加该试题...')
							
						}else{
							// this.$message.success('添加成功');
							this.testList[index].exist = 1;
						}
						// let id = deep_clone(this.testList[index].id)
						// /*用户加入的试题的数组*/
						 this.arrayID.push(this.testList[index].id)
						 this.arrayID = [...new Set(this.arrayID)]

						 	// console.log(this.$store.state.delQuestion, this.arrayID, 1)

						//  /*根据加入试题的数组的id组装杨工新的试卷数组 */
						//  for (var i = 0; i < this.testList.length; i++) {
						//  	if (this.arrayID.includes(this.testList[i].id)) {
						//  		this.questionArray.push(this.testList[i])
						//  	}
						//  }
						 let success = (res=>{
						 	this.$message.success(res.msg)
						 	this.$store.commit('SET_QUESTIONCHANGE', new Date())
						 })
						  let params = '';

						  if (this.$route.query.id) {
						  	params = {
						  		testid: this.$route.query.id,
						  		question_id: obj.id
						  	}
						  }else{
						  	params  = {
						  		testid: this.$route.query.edit,
						  		question_id: obj.id
						  	}
						  }
						
						 this.$ajax.post('api/test/bind_one_question_to_test', params, {func:{success: success}})

					
						
						 // bus.$emit('testChange', this.questionArray);

					break;
					case 3:
						this.testList[index].exist = 0;
						this.arrayID.splice(this.arrayID.indexOf(this.testList[index].id), 1)
						this.questionArray.splice(this.questionArray.indexOf(this.testList[index]), 1)
						this.$store.commit('SET_QUESTIONCHANGE', obj.id)
						// console.log(val);
						bus.$emit('testChange', this.questionArray);
						this.$message.warning('删除成功');

					break;

				}
			},
		}
	}
</script>